from flask import Flask, Blueprint, render_template, request, redirect, jsonify, url_for, session, flash
from applications.models.frontend import *

from applications.view.user.login import bp as login_bp
from applications.view.user.user import bp as user_bp
from applications.view.user.product import register_product_bp  # 导入商品管理蓝图
from applications.view.user.cart import register_cart_bps  # 导入购物车管理蓝图
from applications.view.user.address import register_address_bps  # 导入地址管理蓝图
from applications.view.user.story import register_story_bps  # 导入故事管理蓝图

from applications.view.user.decorators import login_required  # 从新的模块导入装饰器

# 创建前台端,url_prefix='/system',前缀路由/
user = Blueprint('user', __name__)


# 请求前 打印session
@user.before_request
def before_request():
    print('Session before request:', session)


# 前台首页页面路由
@user.route('/')
@user.route('/index', methods=['GET'])
def index():
    user_id = session.get('user_id')  # 从 session 获取用户 ID
    print('indexSession：', session)  # 打印 session 信息

    if user_id:
        user = User.query.get(user_id)
        print(user)
        product_cates = ProductCate.query.all()
        products = Product.query.all()
        articates = ArticleCate.query.order_by(ArticleCate.id).all()
        articles = Article.query.all()
        return render_template('user/index/index.html', user=user, product_cates=product_cates, products=products[0:9],
                               articates=articates, articles=articles)
    else:
        return render_template('user/index/index.html')


# 前台理念页面
@user.route('/idea')
def idea():
    user_id = session.get('user_id')
    print('user', user_id)
    user = User.query.filter(User.id == user_id).first()
    artcates = ArticleCate.query.all()

    # 检查 artcates 是否有足够的元素
    if len(artcates) > 1:
        art2 = artcates[1].articles  # 生日送花
    else:
        art2 = []  # 处理没有足够类别的情况

    # 检查 art2 是否有元素
    if art2:
        return render_template('user/idea/idea.html', user=user, art2=art2[0:1])
    else:
        return render_template('user/idea/idea.html', user=user, art2=[])  # 或者处理 art2 为空的情况


# 前台订单详情页面
@user.route('/order_detail/<int:order_id>')
def order_detail(order_id):
    user_id = session.get('user_id')
    user = User.query.get(user_id) if user_id else None  # 获取用户信息

    if not user_id:
        flash('请先登录！', 'warning')
        return redirect(url_for('login.login', next=request.url))

    # 获取订单信息
    order = Order.query.get(order_id)
    if not order or order.user_id != user_id:
        flash('订单不存在或无权查看！', 'danger')
        return redirect(url_for('user.index'))

    # 获取订单项
    order_items = OrderItem.query.filter_by(order_id=order.id).all()
    order_total = sum(item.price * item.quantity for item in order_items)

    print(f"Order ID: {order.id}, Total: {order_total}, Items: {len(order_items)}")  # Debugging line
    print('order11111:', order)
    return render_template('user/order/order_detail.html', order=order, order_items=order_items,
                           order_total=order_total, user=user)  # 传递用户信息


# 订单删除功能
@user.route('/delete_order/<int:order_id>', methods=['POST'])
@login_required
def delete_order(order_id):
    user_id = session.get('user_id')
    order = Order.query.get(order_id)
    if order and order.user_id == user_id and order.status == 'unpaid':
        # 删除订单及其相关的订单项
        OrderItem.query.filter_by(order_id=order.id).delete()
        db.session.delete(order)
        db.session.commit()
        flash('订单已成功删除！', 'success')
    else:
        flash('无法删除订单！', 'danger')
    return redirect(url_for('user.order_management'))


# 前台订单管理页面
@user.route('/order_management', methods=['GET'])
def order_management():
    user_id = session.get('user_id')
    user = User.query.get(user_id) if user_id else None  # 获取用户信息
    if not user_id:
        flash('请先登录！', 'warning')
        return redirect(url_for('login.login', next=request.url))

    # 获取当前页码，默认为1
    page = request.args.get('page', 1, type=int)
    # 每页显示的订单数量
    per_page = 5

    # 获取用户的所有订单并进行分页
    orders = Order.query.filter_by(user_id=user_id).paginate(page=page, per_page=per_page)

    return render_template('user/order/order_management.html', orders=orders, user=user)


# 注册用户蓝图
def register_user_bps(app: Flask):
    # 在admin_bp下注册子蓝图
    app.register_blueprint(user)  # 主蓝图
    app.register_blueprint(login_bp)  # 登录蓝图
    app.register_blueprint(user_bp)  # 用户蓝图
    register_product_bp(app)  # 注册商品管理蓝图
    register_cart_bps(app)  # 注册购物车管理蓝图
    register_address_bps(app)  # 注册地址管理蓝图
    register_story_bps(app)  # 注册故事管理蓝图
